package com.tiku.service.impl;

import com.aliyun.credentials.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tiku.common.ResultJson;
import com.tiku.controller.DTO.UserCollectionDTO;
import com.tiku.controller.DTO.UserShoucangDTO;
import com.tiku.entity.*;
import com.tiku.mapper.ChapterSubInfoMapper;
import com.tiku.mapper.QuestionTableMapper;
import com.tiku.mapper.UserCollectionMapper;
import com.tiku.service.ChapterInfoService;
import com.tiku.service.UserCollectionService;
import com.tiku.utils.ThreadLocalUtil;
import io.jsonwebtoken.lang.Collections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【user_collection】的数据库操作Service实现
* @createDate 2024-09-25 18:51:42
*/
@Service
public class UserCollectionServiceImpl extends ServiceImpl<UserCollectionMapper, UserCollection>
    implements UserCollectionService{

    @Autowired
    private UserCollectionMapper userCollectionMapper;

    @Autowired
    private QuestionTableMapper questionTableMapper;

    @Autowired
    private ChapterInfoService chapterInfoService;

    @Autowired
    private ChapterSubInfoMapper chapterSubInfoMapper;
//新增收藏
    @Override
    public ResultJson addCollection(String id,String setMealId ,String csiId) {
        if (StringUtils.isEmpty(id)) {
            return ResultJson.error("请先选择题目表!");
        }
        if (questionTableMapper.selectById(id)==null){
            return ResultJson.error("该题目表不存在!");
        }
        String threadLocal = ThreadLocalUtil.getThreadLocal();
        UserCollection userCollection1 = userCollectionMapper.selectOne(new LambdaQueryWrapper<UserCollection>().eq(UserCollection::getUserQuestionTable, id).eq(UserCollection::getUserId, threadLocal));
        if (userCollection1!=null){
            return ResultJson.error("您已收藏该题目表!");
        }
        UserCollection userCollection=new UserCollection();
        userCollection.setId(null);
        userCollection.setUserId(threadLocal);
        userCollection.setCreateTime(new Date());
        userCollection.setUserQuestionTable(id);
        String setMealId1 = userCollectionMapper.getSetMealId(id);
        if (!StringUtils.isEmpty(setMealId1)){
            setMealId =setMealId1;
        }


        userCollection.setSetMealId(setMealId);
        userCollection.setCsiId(csiId);
        int insert = userCollectionMapper.insert(userCollection);
        return insert>0?ResultJson.success(null):ResultJson.sysError();
    }

//    查询
    @Override
    public Boolean selectCollectionDO(String id) {
        return userCollectionMapper.selectCount(new QueryWrapper<UserCollection>().lambda()
                .eq(UserCollection::getUserId,ThreadLocalUtil.getThreadLocal())
                .eq(UserCollection::getUserQuestionTable,id))>0;
    }

    @Override
    public ResultJson deleteCollection(String id) {
        if (StringUtils.isEmpty(id)){
            return ResultJson.error("参数不能为空!");
        }
        userCollectionMapper.delete(new QueryWrapper<UserCollection>().lambda()
                .eq(UserCollection::getUserId,ThreadLocalUtil.getThreadLocal())
                .eq(UserCollection::getUserQuestionTable,id));
        return ResultJson.success(null);
    }

    @Override
    public ResultJson selectCollection(String setMealId) {
        String threadLocal = ThreadLocalUtil.getThreadLocal();
        if (StringUtils.isEmpty(threadLocal)){
            return ResultJson.error("参数不能为空!");
        }
        //查询的是chapter_info
        List<UserCollectionDTO> userCollection = userCollectionMapper.selectCollection(threadLocal,setMealId);

            //查询的是chapter_sub_info
        List<UserCollectionDTO>  userCollection2=userCollectionMapper.selectCollection2(threadLocal,setMealId);
        userCollection.addAll(userCollection2);

        for (UserCollectionDTO userCollectionDTO : userCollection) {
            QuestionTable questionTable = questionTableMapper.selectById(userCollectionDTO.getId());
            questionTable.setCollectFlagDO(true);
            userCollectionDTO.setQuestionTable(questionTable);
        }
        return ResultJson.success(userCollection) ;
    }
    @Override
    public ResultJson selectCollections(String csiId) {
        String userId = ThreadLocalUtil.getThreadLocal();
        if (StringUtils.isEmpty(userId)) {
            return ResultJson.error("参数不能为空!");
        }


        List<UserCollectionDTO> userCollection = userCollectionMapper.selectCollections(userId,csiId);
        Map<String, List<UserCollectionDTO>> collect = userCollection.stream()
                .collect(Collectors.groupingBy(UserCollectionDTO::getChapterName));
        if (Collections.isEmpty(userCollection)){
            userCollection = userCollectionMapper.selectCollections2(userId,csiId);
            collect = userCollection.stream()
                    .collect(Collectors.groupingBy(UserCollectionDTO::getChapterId));
        }



        List<Map<String,Object>> obj= new ArrayList<>();
        Set<String> strings = collect.keySet();
        for (String key : strings) {
            Map<String, Object> newList=new HashMap<>();
            ChapterInfo byId = chapterInfoService.getById(key);
            if (Objects.isNull(byId)){
                ChapterSubInfo chapterSubInfo = chapterSubInfoMapper.selectById(key);
                if (Objects.isNull(chapterSubInfo)){
                    newList.put("chapterNameFather",key);
                }else {
                    newList.put("chapterNameFather",chapterSubInfo.getChapterName());
                }

            }else {
                newList.put("chapterNameFather",byId.getChapterName());
            }

            newList.put("list", collect.get(key));
            obj.add(newList);
        }

        return ResultJson.success(obj) ;
    }


    @Override
    public ResultJson selectCollectionAssembly(String id) {
        String threadLocal = ThreadLocalUtil.getThreadLocal();
        if (StringUtils.isEmpty(id)){
            return ResultJson.error("参数不能为空!");
        }
        if (StringUtils.isEmpty(threadLocal)){
            return ResultJson.error("参数不能为空!");
        }
        List<UserShoucangDTO> userCollection = userCollectionMapper.selectCollectionAssembly(id,threadLocal);
        return ResultJson.success(userCollection);
    }

}




